package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PermissionName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.List;

@Controller
@RequestMapping("permission")
public class PermissionController {
    @Autowired
    private IPermissionService service;

    @RequestMapping("")
    public String index(){
        return "permission/list";
    }

    @RequestMapping("list")
    @ResponseBody
    @RequiresPermissions("permission:data")
    @PermissionName("权限列表")
    public PageResult list(QueryObject qo){ //权限没有高级查询
        //在角色对话框添加权限时以便显示出所有权限
        List<Permission> permissions = service.list();
        PageResult result = new PageResult();
        result.setTotal(permissions.size());
        result.setRows(permissions);
        return result;
    }

    @RequestMapping("load")
    @ResponseBody
    @RequiresPermissions("permission:load")
    @PermissionName("权限加载")
    public JsonResult load(){   //=======权限没有保存,只有加载=======
        JsonResult result = new JsonResult();
        try {
            System.out.println(("1111111111111111111"));
            service.load();
            System.out.println(("2222222222222222222"));

        } catch (Exception e) {
            e.printStackTrace();
            result = new JsonResult("权限加载失败");
        }
        return result;
    }

    @RequestMapping("update")
    @ResponseBody
    @RequiresPermissions("permission:update")
    @PermissionName("权限更新")
    public JsonResult update(Permission permission){
        JsonResult result = new JsonResult();
        try {
            service.update(permission);
        } catch (Exception e) {
            e.printStackTrace();
            result = new JsonResult("编辑失败");
        }
        return result;
    }

    @RequestMapping("delete")
    @ResponseBody
    @RequiresPermissions("permission:changeState")
    @PermissionName("权限删除")
    public JsonResult delete(Long id){
        JsonResult result = new JsonResult();
        try {
            service.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            result = new JsonResult("删除失败");
        }
        return result;
    }


    //根据角色id查询其对应的所有权限
    @RequestMapping("queryPermissionByRoleId")
    @ResponseBody
    public List<Permission> queryPermissionByRoleId(Long roleId){
        return service.queryPermissionByRoleId(roleId);
    }



}
